package com.agent.commons.utils;

import cn.hutool.captcha.GifCaptcha;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;

import java.io.ByteArrayOutputStream;
import java.util.Map;

/**
 * 生成验证码以及图片验证码的工具类
 */
public class CaptchaUtil {
    private static final int width=200;
    private static final int height=100;
    private static final int fontSize=5;
    private static final String base="1234567890abcdefghijklmnopqrstuvwxyz";
    /**
     * 生成图片验证码
     */
    public static Map<String, ByteArrayOutputStream> createCaptchaPicture() {
        GifCaptcha gif=new GifCaptcha(width,height,fontSize);
        //生成验证码
        String code=gif.getCode();
        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
        //将图片写入字节输出流中
        gif.write(outputStream);
        return Map.of(code,outputStream);
    }

    /**
     * 生成自定义位数的验证码
     */
    public static String createCaptcha(int size) {
        RandomGenerator randomGenerator=new RandomGenerator(base, size);
        LineCaptcha lineCaptcha=new LineCaptcha(width,height);
        lineCaptcha.setGenerator(randomGenerator);
        lineCaptcha.createCode();
        return lineCaptcha.getCode();
    }
}
